package com.wf.course.web.controller.course;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.utils.page.PageBean;
import com.wf.course.model.course.CourseChapter;
import com.wf.course.model.course.CourseForm;
import com.wf.course.model.course.CourseWork;
import com.wf.course.service.ICourseChapterService;
import com.wf.course.service.ICourseInfoService;
import com.wf.course.service.ICourseWorkService;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("course/work")
public class CourseWorkController {

    @Autowired
    private ICourseWorkService courseWorkService;

    @Autowired
    private ICourseInfoService courseInfoService;

    @Autowired
    private ICourseChapterService courseChapterService;

    @RequestMapping("toFormBuild/{id}")
    public String toFormBuild(@PathVariable("id") Integer id, Model model) {
        if (id > 0) {
            model.addAttribute("courseWork", courseWorkService.searchCourseWork(id));
        }
        return "course/courseWorkFormBuild";
    }

    @ResponseBody
    @RequestMapping("previewForm/{id}")
    public CourseWork previewForm(@PathVariable("id") Integer id) {
        CourseWork courseWork = courseWorkService.searchCourseWork(id);
        return courseWork;
    }

    @RequestMapping("list")
    public String work(Model model, Integer pageNo, Integer pageSize, CourseWork courseWork) {
        try {
            PageBean page = new PageBean<>(pageNo, pageSize);
            page.setObj(courseWork);
            courseWorkService.list(page);
            page.setUrl("course/work/list");
            StringBuilder builder = new StringBuilder();
            for (Field f : courseWork.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (null != f.get(courseWork) && StringUtils.isNotBlank(f.get(courseWork).toString())) {
                    builder.append("&" + f.getName() + "=" + f.get(courseWork));
                }
            }
            page.setParams(builder.toString());
            model.addAttribute("page", page);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "course/courseWorkList";
    }

    @RequestMapping("pageLoad/{id}")
    public String pageLoad(@PathVariable("id") Integer id, Model model) {
        model.addAttribute("courses", courseInfoService.queryCourses());
        model.addAttribute("chapters", new Gson().toJson(courseChapterService.queryCourseChapters().stream()
                .collect(Collectors.groupingBy(CourseChapter::getCourseId))));
        if (id > 0) {
            model.addAttribute("courseWork", courseWorkService.searchCourseWork(id));
        }
        return "course/courseWorkEdit";
    }

    @RequestMapping("insertOrUpdate")
    public String insertOrUpdate(CourseWork courseWork) {
        if (courseWork.getId() != null) {
            courseWorkService.update(courseWork);
        } else {
            courseWork.setStatus(2);
            courseWorkService.insert(courseWork);
        }
        return "redirect:/course/work/list";
    }

    @RequestMapping("delete/{id}")
    public String delete(@PathVariable("id") Integer id) {

        return "redirect:/course/work/list";
    }

    @RequestMapping("updateForm")
    @ResponseBody
    public Map updateForm(@RequestBody CourseWork courseWork) {
        Map<String, Integer> result = new HashMap<>();
        try {
            result.put("status", 200);
            courseWorkService.updateForm(courseWork);
        } catch (Exception e) {
            result.put("status", 500);
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("memberWorkList")
    public String memberWorkList(Model model, Integer pageNo, Integer pageSize, CourseWork courseWork) {
        try {
            PageBean page = new PageBean<>(pageNo, pageSize);
            page.setObj(courseWork);
            courseWorkService.memberWorkList(page);
            page.setUrl("course/work/memberWorkList");
            StringBuilder builder = new StringBuilder();
            for (Field f : courseWork.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (null != f.get(courseWork) && StringUtils.isNotBlank(f.get(courseWork).toString())) {
                    builder.append("&" + f.getName() + "=" + f.get(courseWork));
                }
            }
            page.setParams(builder.toString());
            model.addAttribute("page", page);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "course/memberWorkList";
    }

    @RequestMapping("goToComment/{id}")
    public String goToComment(@PathVariable("id") Integer id, Model model) {
        try {
            CourseWork memberWork = courseWorkService.searchMemberWork(id);
            List<CourseForm> list = new Gson().fromJson(memberWork.getData(),
                    new TypeToken<List<CourseForm>>() {
                    }.getType());
            Map<String, List<CourseForm>> map = list.stream().collect(Collectors.groupingBy(CourseForm::getName));
            if (!map.containsKey("老师点评")) {
                list.add(new CourseForm(UUID.randomUUID().toString().replaceAll("-", "")
                        , "老师点评", "textarea", "", "", new ArrayList<>()));
            }
            memberWork.setCourseForms(list);
            model.addAttribute("memberWork", memberWork);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "course/memberWorkComment";
    }

    @RequestMapping("comment")
    public String comment(CourseWork courseWork) {
        try {
            CourseWork memberWork = courseWorkService.searchMemberWork(courseWork.getId());
            List<CourseForm> list = new Gson().fromJson(memberWork.getData(),
                    new TypeToken<List<CourseForm>>() {
                    }.getType());
            Map<String, List<CourseForm>> map = list.stream().collect(Collectors.groupingBy(CourseForm::getName));
            if (!map.containsKey("老师点评")) {
                list.add(new CourseForm(UUID.randomUUID().toString().replaceAll("-", "")
                        , "老师点评", "textarea", courseWork.getData(), "", new ArrayList<>()));
            } else {
                list.get(list.size() - 1).setValue(courseWork.getData());
            }
            courseWork.setData(new Gson().toJson(list));
            courseWorkService.updateMemberWork(courseWork);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/course/work/memberWorkList";
    }

    @RequestMapping("deleteMemberWorkByChapterId/{chapterId}")
    public String deleteMemberWorkByChapterId(@PathVariable("chapterId") Integer chapterId) {
        courseWorkService.deleteMemberWorkByChapterId(chapterId);
        return "redirect:/course/work/list";
    }
}